package com.stellar.core.util;

import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicLong;

public class NumericIdGenerator {
    // 时间基准点（2024-01-01 00:00:00 UTC）
    private static final long EPOCH = 1704067200000L;

    // 时间分片长度（5秒为一个时间窗口）
    private static final long TIME_SHARD = 5000L;

    // 最后时间分片和序列号
    private static final AtomicLong LAST_SHARD = new AtomicLong(-1L);
    private static final AtomicLong SEQUENCE = new AtomicLong(0);

    private static final SecureRandom random = new SecureRandom();

    // 生成9位数字ID
    public static synchronized long generateId() {
        long currentShard = (System.currentTimeMillis() - EPOCH) / TIME_SHARD;
        long sequence = SEQUENCE.getAndIncrement();

        // 时间窗口切换时重置序列号
        if (currentShard > LAST_SHARD.get()) {
            SEQUENCE.set(0);
            sequence = 0;
            LAST_SHARD.set(currentShard);
        }

        // ID结构：时间分片（5位） + 序列号（4位）
        return (currentShard % 100000L) * 10000 + (sequence % 10000);
    }

    // 随机数方案（适合低并发）
    public static String generateRandomId() {
        long timestampPart = System.currentTimeMillis() % 100000000L; // 8位时间戳
        int randomPart = random.nextInt(90) + 10;   // 2位随机数（10-99）

        StringBuilder sb = new StringBuilder()
                .append(timestampPart)
                .append(randomPart);

        // 截取并确保9位长度
        String id = sb.toString().substring(0, 9);

        // 首字母非零保护
        if (id.startsWith("0")) {
            return (random.nextInt(9) + 1) + id.substring(1);
        }
        return id;
    }

    // 带机器ID的分布式方案
    public static long generateDistributedId(int machineId) {
        long currentShard = (System.currentTimeMillis() - EPOCH) / TIME_SHARD;
        long sequence = SEQUENCE.getAndIncrement();

        // ID结构：时间分片（4位） + 机器ID（2位） + 序列号（3位）
        return (currentShard % 10000L) * 100000
                + (machineId % 100) * 1000
                + (sequence % 1000);
    }

    public static void main(String[] args) {
        // 测试生成
        System.out.println("Sequential ID: " + generateId());
        System.out.println("Random ID: " + generateRandomId());
        System.out.println("Distributed ID: " + generateDistributedId(5));
    }
}